<template>
  <div class="page-content">
    <el-button @click="showDialog('add')" v-ripple>新增</el-button>

    <art-table :data="tableData" :loading="loading" :currentPage="1" :pageSize="10" :total="total">
      <template #default>
        <el-table-column label="用户名称" prop="name" />
        <el-table-column label="手机号" prop="telephone" align="center">
          <template #default="scope">
            <span v-if="scope.row.telephone">{{ scope.row.telephone }}</span>
            <i v-else class="iconfont-sys">&#xe665;</i>
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="status" #default="scope" align="center">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
            {{ scope.row.status === 1 ? '启用' : '停用' }}
          </el-tag>
        </el-table-column>
        <el-table-column label="备注" prop="desc" align="center" />
        <el-table-column label="创建日期" prop="create_time" align="center" />
        <el-table-column fixed="right" label="操作" width="150px">
          <template #default="scope">
            <ArtButtonTable type="edit" @click="showDialog('edit', scope.row)" />
            <ArtButtonTable type="delete" @click="deleteUser(scope.row)" />
          </template>
        </el-table-column>
      </template>
    </art-table>

    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加角色' : '编辑角色'"
      width="40%"
    >
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="密码" prop="pwd">
          <el-input type="password" show-password v-model="formData.pwd" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="级别" prop="admin_type">
          <el-select v-model="formData.admin_type">
            <el-option label="超级管理员" :value="1"></el-option>
            <el-option label="普通角色" :value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input type="number" v-model="formData.phone" placeholder="请输入手机号码" />
        </el-form-item>
        <el-form-item label="备注" prop="desc">
          <el-input type="textarea" v-model="formData.desc" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">提交</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="pwdDialog" title="修改密码" width="30%">
      <el-form ref="formPwdRef" :model="formPwd" :rule="rulesPwd" label-width="80px">
        <el-form-item label="密码" prop="new_password">
          <el-input
            type="password"
            v-model="formPwd.new_password"
            show-password
            placeholder="请输入密码"
            maxlength="20"
          ></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="sure_new_password">
          <el-input
            type="password"
            v-model="formPwd.sure_new_password"
            show-password
            placeholder="请再次输入密码"
            maxlength="20"
          ></el-input>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { FormInstance } from 'element-plus'
  import { ElMessageBox, ElMessage } from 'element-plus'
  import type { FormRules } from 'element-plus'
  import { AdminService } from '@/api/admin'

  const dialogType = ref('add')
  const dialogVisible = ref(false)
  const pwdDialog = ref(false)
  const formPwdRef = ref(null)

  const formData = reactive({
    name: '',
    pwd: '',
    admin_type: '',
    phone: '',
    desc: ''
  })

  const formPwd = reactive({
    new_password: '',
    sure_new_password: ''
  })

  const total = ref(0)
  const queryParams = reactive({
    page: 1,
    size: 10
  })

  const loading = ref(false)

  let tableData = reactive([])

  // 获取商品列表
  const getPage = async () => {
    loading.value = true
    const { data } = await AdminService.getListAmin(queryParams)
    total.value = data.total
    Object.assign(tableData, data.data)
    loading.value = false
  }
  getPage()

  const showDialog = (type: string, row?: any) => {
    dialogType.value = type
    if (type === 'add') {
      dialogVisible.value = true
    } else {
      pwdDialog.value = true
    }
  }

  const deleteUser = (row: any) => {
    ElMessageBox.confirm('确定要删除该' + row.name + '角色吗？', '删除角色', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'error'
    })
      .then(() => {
        return AdminService.delAdmin(row.id)
      })
      .then(() => {
        getPage()
        ElMessage.success('删除成功')
      })
  }

  const validatePass = (rule: any, value: any, callback: any) => {
    if (value === '') {
      callback(new Error('请输入密码'))
    } else {
      if (formPwd.sure_new_password !== '') {
        if (!formPwdRef.value) return
        formPwdRef.value.validateField('sure_new_password')
      }
      callback()
    }
  }
  const validatePass2 = (rule: any, value: any, callback: any) => {
    if (value === '') {
      callback(new Error('请再次输入密码'))
    } else if (value !== formPwd.new_password) {
      callback(new Error('两次输入的密码不一致'))
    } else {
      callback()
    }
  }
  const rules = reactive<FormRules>({
    name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
    pwd: [{ required: true, message: '请输入密码', trigger: 'blur' }]
  })

  const rulesPwd = reactive<FormRules>({
    new_password: [{ required: true, trigger: 'blur', validator: validatePass }],
    sure_new_password: [{ required: true, trigger: 'blur', validator: validatePass2 }]
  })
  const formRef = ref<FormInstance>()

  const handleSubmit = () => {
    if (!formRef.value) return
    formRef.value.validate(async (valid) => {
      if (valid) {
        if (dialogType.value === 'add') {
          await AdminService.addAdmin(formData)
        } else {
          await AdminService.updateAdmin(formData)
        }
        await getPage()
        ElMessage.success(dialogType.value === 'add' ? '添加成功' : '修改成功')
        dialogVisible.value = false
      }
    })
  }
</script>

<style lang="scss" scoped>
  .page-content {
    width: 100%;
    height: 100%;

    .user {
      .avatar {
        width: 40px;
        height: 40px;
        border-radius: 6px;
      }

      > div {
        margin-left: 10px;

        .user-name {
          font-weight: 500;
          color: var(--art-text-gray-800);
        }
      }
    }
  }
</style>
